package org.baygo.view.api.listener;

import org.babygo.connect.NettyFileOperator;
import org.baygo.view.api.impl.MyViewOperator;
import org.baygo.view.api.listener.mycomponent.MyButton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class ConnectButtonActionListener extends MouseAdapter{
	private Logger log = LoggerFactory.getLogger(ConnectButtonActionListener.class);

	private NettyFileOperator client = new NettyFileOperator();
	{
		NettyFileOperator.setViewOperator(MyViewOperator.getMyOperator());
	}
    private JTextArea logArea;
    private MyButton connectButton;
    private String ip;
    private int port;

    public ConnectButtonActionListener(JTextArea logArea, MyButton connectButton){
    	this.logArea = logArea;
    	this.connectButton = connectButton;
    }

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getButton()==MouseEvent.BUTTON1 && e.getClickCount() == 1){
			doWork();
		}
	}

	public void doWork() {
		SwingWorker <String, Boolean> server = new SwingWorker<String, Boolean>(){

			@Override
			protected String doInBackground() throws Exception {
				log.info("连接到远程");
				if (!connectButton.isRed()){
					client.closeClient();
					publish(false);
					log.info("断开连接");
					connectButton.setBackground(Color.red);
					connectButton.turnRed();
					return "断开连接";
				}
				String[] adress = connectButton.getText().split(" +");
				ip = adress[0];
				port = Integer.parseInt(adress[1]);
				MyViewOperator.getMyOperator().addNewConnectButoon(ip, adress[1], connectButton);
				publish(client.connect(ip, port));
				return "远程连接结束";
			}

			@Override
			protected void process(List<Boolean> chunks) {
				log.info("process");
				for (Boolean result : chunks) {
					if (result==true){
						logArea.append("远程连接成功!\n");
						connectButton.setBackground(Color.green);
						connectButton.turnGreen();
					}
					if (result == false){
						logArea.append(String.format("到:%s-%s 的远程连接断开!\n", ip, port));
						connectButton.turnRed();
					}
				}
			}
		};
		server.execute();
	}

}